package org.adorsys.aderp.cash.web.ext;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adorsys.aderp.aderplogin.roles.ContextualRoleVoter;
import org.adorsys.aderp.aderplogin.roles.SimpleContextualAttrEval;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping({"/accessdenied"})
@Controller
public class AccessDeniedController {
	
	private SimpleContextualAttrEval rolePPCashier = new SimpleContextualAttrEval("PP_ADERPCASH_CASHIER");
	private SimpleContextualAttrEval rolePPBackOffice = new SimpleContextualAttrEval("PP_ADERPCASH_SUPPORT");

	public static final String ACCESS_DENIED_PAGE = "accessdenied";

	@RequestMapping(method = RequestMethod.GET)
	public String selectPage(Model uiModel, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	UserDetails userDetails = SecurityUtils.getUserDetails();
    	
    	if(userDetails==null) return ACCESS_DENIED_PAGE;
    	Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
    	for (GrantedAuthority grantedAuthority : authorities) {
			if(ContextualRoleVoter.ACCESS_GRANTED == rolePPCashier.match(grantedAuthority.getAuthority())){
				uiModel.addAttribute("linkName", "cashier");
				uiModel.addAttribute("url", "/cashier");
			} else if (ContextualRoleVoter.ACCESS_GRANTED == rolePPBackOffice.match(grantedAuthority.getAuthority())){
				uiModel.addAttribute("linkName", "support");
				uiModel.addAttribute("url", "/support");
			}
		}
    	return ACCESS_DENIED_PAGE;
	}
}
